<?php


namespace app\index\service;

use app\index\model\Agent;
use app\index\model\CommissionAssessmentWithdraw;
use app\index\model\Configuration;
use app\index\model\RechargeRecord;
use app\index\model\User;
use app\index\model\UserCash;
use app\utils\CheckWithdraw;
use think\db\Query;
use think\Exception;

class CommissionAssessmentWithdrawService
{

    private $user;

    private $agent;

    private $baseIn;

    private $serialNum;

    private $integralBalance;

    public function __construct()
    {
        global $user, $baseIn;
        $this->user = User::find($user['id']);
        $this->agent = Agent::where('user_id', $this->user->id)->find();
        $this->baseIn = $baseIn;
        $this->serialNum = md5(uniqid() . time());
        $integralBalance = Configuration::where('mall_id', $this->user->mall_id)
            ->where(['type' => "integralBalance"])
            ->value("configuration");
        if (empty($integralBalance))
            throw new Exception("未完善支付配置", HTTP_NOTACCEPT);
        $this->integralBalance = json_decode($integralBalance, true);

    }


    public function total(float $amount, ?string $remark)
    {
        if (!isset($this->integralBalance['agent_withdraw']) || empty($this->integralBalance['agent_withdraw']))
            throw new Exception("暂不支持提现", HTTP_NOTACCEPT);
        if (!isset($this->integralBalance['agent_withdraw_type']) || !in_array(2, $this->integralBalance['agent_withdraw_type']))
            throw new Exception("暂不支持提现至余额", HTTP_NOTACCEPT);

        $userCash = UserCash::where(['user_id' => $this->user['id']])->lock(true)->find();
        $service_charge = 0;

        if ($userCash->assessment < $amount) {
            $data['remark'] = "余额不足";
            throw new Exception("余额不足", HTTP_NOTACCEPT);
        }
        $userCash->inc("total", $amount)
//            ->inc("recharge", $amount)
            ->dec("assessment", $amount)
            ->inc("assessment_withdraw", $amount)
            ->update();
        $data['status'] = 1;
        CommissionAssessmentWithdraw::create([
            "agent_id" => $this->agent->id,
            "withdraw" => $amount,
            'mall_id' => $userCash->mall_id,
            'service_charge' => $service_charge,
            "type" => 2,
            "status" => 1,
            'remark' => $remark,
            'serial_num' => $this->serialNum,
            'is_online' => 1
        ]);
        return [HTTP_CREATED, "提现至余额成功"];

    }


    public function save(int $user_id, float $amount, ?string $remark = ''): array
    {
        if (!isset($this->integralBalance['agent_withdraw']) || empty($this->integralBalance['agent_withdraw']))
            throw new Exception("暂不支持提现", HTTP_NOTACCEPT);
        $id = Agent::where('user_id', $user_id)->value('id');
        $usercash = UserCash::where('user_id', $user_id)->find();
        if ($amount > $usercash->assessment) return [HTTP_INVALID, '余额不足'];
        $usercash->inc('withdraw', $amount)
            ->dec('assessment', $amount)
            ->inc('assessment_withdraw', $amount)
            ->update();
        $withdraw = CommissionAssessmentWithdraw::create([
            'agent_id' => $id,
            'withdraw' => $amount,
            'mall_id' => $usercash->mall_id,
            'type' => 1,
            'status' => 1,
            'remark' => $remark,
            'serial_num' => md5(uniqid() . time())
        ]);
        return [HTTP_CREATED, $withdraw];
    }

    public function findAll(int $user_id, ?int $status, int $page, int $size): array
    {
        $where = [];
        if (!is_null($status))
            $where[] = ['status', '=', $status];
        $list = CommissionAssessmentWithdraw::field('id,agent_id,withdraw,type,serial_num,status,remark,create_time')
            ->where('agent_id', 'in', function (Query $query) use ($user_id) {
                $query->name('agent')->field('id')->where('user_id', $user_id);
            })
            ->where($where)
            ->order('create_time DESC')
            ->paginate(['page' => $page, 'list_rows' => $size]);
        return [HTTP_SUCCESS, $list];
    }

    public function read(int $id): array
    {
        $info = CommissionAssessmentWithdraw::field('id,type,status,withdraw,serial_num,remark,create_time')->find($id);
        return [HTTP_SUCCESS, $info];
    }

    public function apply(array $data): array
    {
        if (!isset($this->integralBalance['agent_withdraw']) || empty($this->integralBalance['agent_withdraw']))
            throw new Exception("暂不支持提现", HTTP_NOTACCEPT);
        $user = $this->user;
        $time = CommissionAssessmentWithdraw::where('agent_id', $this->agent->id)
            ->where('status', 0)
            ->order('create_time DESC')
            ->value('create_time');
        if (!empty($time) && strtotime($time) > time() - 5)
            throw new Exception('请不要短时间内多次操作内多次操作', HTTP_INVALID);
        $userCash = UserCash::where(['user_id' => $this->user['id']])->lock(true)->find();
        if ($userCash->assessment < $data['withdraw'])
            throw new Exception("余额不足", HTTP_NOTACCEPT);
        $util = new CheckWithdraw($this->integralBalance);
        $amount = $util->commissionAssessment($data['withdraw']);
        $find = CommissionAssessmentWithdraw::create([
            'agent_id' => $this->agent->id,
            'withdraw' => $data['withdraw'],
            'mall_id' => $userCash->mall_id,
            'service_charge' => $amount,
            'is_online' => 0,
            'type' => 3,
            'card' => $data['card'],
            'status' => 0,
            'remark' => $data['remark'] ?? '',
            'serial_num' => $this->serialNum,
            'create_time' => now()
        ]);
        $userCash->inc("assessment_withdraw", $data['withdraw'])
            ->dec('assessment', $data['withdraw'])
            ->update(['update_time' => now()]);
        if (empty($find['id']))
            throw new Exception('申请失败', HTTP_INVALID);
        return [HTTP_SUCCESS, $find];
    }

    public function wx(float $amount, ?string $remark = ''): array
    {
        if (!isset($this->integralBalance['agent_withdraw']) || empty($this->integralBalance['agent_withdraw']))
            throw new Exception("暂不支持提现", HTTP_NOTACCEPT);
        $checkWithdraw = new CheckWithdraw($this->integralBalance);
        $agent = $checkWithdraw->commissionAssessment($amount);
        $userCash = UserCash::where(['user_id' => $this->user['id']])->lock(true)->find();
        if ($userCash->assessment < $amount) {
            $data['remark'] = "可提现金额不足";
            throw new Exception("可提现金额不足", HTTP_NOTACCEPT);
        }
        $userCash
            ->inc("assessment_withdraw", $amount)
            ->dec('assessment', $amount)
            ->update(['update_time' => now()]);
        CommissionAssessmentWithdraw::create([
            'agent_id' => $this->agent->id,
            'mall_id' => $userCash->mall_id,
            'withdraw' => $amount,
            'service_charge' => $agent,
            'is_online' => 1,
            'type' => 1,
            'status' => 0,
            'remark' => $remark,
            'serial_num' => $this->serialNum,
            'create_time' => now()
        ]);
        return [HTTP_CREATED, "发起提现申请成功"];
    }
}